package org.sampleSpringFramework.mvc.render.impl;

import org.omg.PortableInterceptor.RequestInfo;
import org.sampleSpringFramework.mvc.common.ModelAndView;
import org.sampleSpringFramework.mvc.processor.RequestProcessorChain;
import org.sampleSpringFramework.mvc.render.ResultRender;
import org.sampleSpringFramework.util.ValidationUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 返回视图的使用使用的结果渲染器
 */
public class ViewResultRender implements ResultRender {

	public static final String VIEW_PATH = "/templates/";
	private ModelAndView modelAndView;

	/**
	 * 对传入的参数处理，初始化	modelAndView成员变量
	 * @param result controller的方法执行完后的返回值
	 */
	public ViewResultRender(Object result) {
		if(result instanceof ModelAndView){
			//1.如果入参类型是ModelAndView，则直接赋值给成员变量
			this.modelAndView = (ModelAndView)result;
		}else if(result instanceof String){
			//2、如果返回的结果是string类型，说明是路径
			this.modelAndView = new ModelAndView().setViewPath((String)result);
		}else {
			//3.针对其他情况，则直接抛出异常
			throw new RuntimeException("自研框架对视图的渲染，只支持controller方法执行后的返回值类型为ModelAndView类型" +
					"或者，返回值为String类型，代表页面路径");
		}
	}

	/**
	 * 将请求处理结果，按照路径转发到对应视图进行展示
	 * @param requestProcessorChain
	 * @throws Exception
	 */
    @Override
	public void render (RequestProcessorChain requestProcessorChain) throws Exception {
    	// 获取request、response，将数据转发给JSP的时候需要使用
		HttpServletRequest request = requestProcessorChain.getRequest();
		HttpServletResponse response = requestProcessorChain.getResponse();
		String viewPath = modelAndView.getViewPath();
		Map<String, Object> model = modelAndView.getModel();
		// 封装数据到Request中
		if(!ValidationUtil.isEmpty(model)){
			for(Map.Entry<String,Object> entry: model.entrySet()){
				String attributeName = entry.getKey();
				Object attributeValue = entry.getValue();
				request.setAttribute(attributeName,attributeValue);
			}
		}
		// 将包含Request，Response的请求转发给JSP页面
		request.getRequestDispatcher(VIEW_PATH +viewPath).forward(request,response);
	}
}
